var express = require('express');
var router = express.Router();
// 连接mongodb
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://193.112.50.226:27017/';

// 检查登录状态
router.get((req,res,next)=>{
	console.log(req.url)
	if(!req.session.uname && req.url != '/login' && req.url != '/'){
		res.redirect('/login');
	}else{
		next();
	}
});

// 获取当前时间
function getNowDate() {
	var date = new Date();
	var sign1 = "-";
	var sign2 = ":";
	var year = date.getFullYear() // 年
	var month = date.getMonth() + 1; // 月
	var day  = date.getDate(); // 日
	var hour = date.getHours(); // 时
	var minutes = date.getMinutes(); // 分
	var seconds = date.getSeconds() //秒
	// 给一位数数据前面加 “0”
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (day >= 0 && day <= 9) {
		day = "0" + day;
	}
	if (hour >= 0 && hour <= 9) {
		hour = "0" + hour;
	}
	if (minutes >= 0 && minutes <= 9) {
		minutes = "0" + minutes;
	}
	if (seconds >= 0 && seconds <= 9) {
		seconds = "0" + seconds;
	}
	var currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds;
	return currentdate;
}

// 一开始去到主页 
router.get('/', function(req, res, next) {
	MongoClient.connect(url, function (err, db) {
	    if (err) throw err;
	    const pageSize = 6;
	    var page;
	    page=req.query.page;
	    // 默认第一页
	    if(isNaN(page)){
	    	page = 1;
    	}
	    var dbase = db.db("blog");
	    var images = ['/images/1.jpg','/images/3.jpg','/images/2.jpg'];
	    var des =['这是第一个描述','这是第二个描述','这是第三个描述']
	    dbase.collection("blog").count(function(err,count){
	    	var sumPage = Math.ceil(count/pageSize);
		    dbase.collection("blog").find({}).limit(pageSize).skip(pageSize*(page-1)).sort({"date":-1}).toArray(function(err,result) {
		        if (err) throw err;
	    	    res.render('index',{data:result,sumPage:sumPage,username:req.session.uname,images:images,des:des})        
		    });
	    })
	});
});

// 点击养生去到养生页面
router.get('/yangsheng', function(req, res, next) {
	MongoClient.connect(url, function (err, db) {
	    if (err) throw err;
	    const pageSize = 6;
	    var page;
	    page=req.query.page;
	    // 默认第一页
	    if(isNaN(page)){
	    	page = 1;
    	}
	    var dbase = db.db("blog");
	    dbase.collection("blog").find({type:'佛系养生'}).toArray(function(err,result2) {
		    dbase.collection("blog").find({type:'佛系养生'}).limit(pageSize).skip(pageSize*(page-1)).sort({"date":-1}).toArray(function(err,result) {
		        if (err) throw err;
		        var sumPage = Math.ceil(result2.length/pageSize);
	    	    res.render('index',{data:result,sumPage:sumPage,username:req.session.uname})        
		    });
	    });
	});
});

// 点击美食去到美食页面
router.get('/meishi', function(req, res, next) {
	MongoClient.connect(url, function (err, db) {
	    if (err) throw err;
	    const pageSize = 6;
	    var page;
	    page=req.query.page;
	    // 默认第一页
	    if(isNaN(page)){
	    	page = 1;
    	}
	    var dbase = db.db("blog");
	    dbase.collection("blog").find({type:'佛系美食'}).toArray(function(err,result2) {
		    dbase.collection("blog").find({type:'佛系美食'}).limit(pageSize).skip(pageSize*(page-1)).sort({"date":-1}).toArray(function(err,result) {
		        if (err) throw err;
		        var sumPage = Math.ceil(result2.length/pageSize);
	    	    res.render('index',{data:result,sumPage:sumPage,username:req.session.uname})        
		    });
	    });
	});
});

// 点击护肤去到护肤页面
router.get('/hufu', function(req, res, next) {
	MongoClient.connect(url, function (err, db) {
	    if (err) throw err;
	    const pageSize = 6;
	    var page;
	    page=req.query.page;
	    // 默认第一页
	    if(isNaN(page)){
	    	page = 1;
    	}
	    var dbase = db.db("blog");
	    dbase.collection("blog").find({type:'佛系护肤'}).toArray(function(err,result2) {
		    dbase.collection("blog").find({type:'佛系护肤'}).limit(pageSize).skip(pageSize*(page-1)).sort({"date":-1}).toArray(function(err,result) {
		        if (err) throw err;
		        var sumPage = Math.ceil(result2.length/pageSize);
	    	    res.render('index',{data:result,sumPage:sumPage,username:req.session.uname})        
		    });
	    });
	});
});

// 密码检测
router.post('/check_pass', function(req, res, next) {
	console.log('check_pass/post');
	MongoClient.connect(url, function (err, db) {
    	var dbase = db.db("blog");
    	if (err) throw err;
    	else{
    		dbase.collection("user").find({username:req.body.name}).toArray(function(err,result2) {
        		if (err) throw err;
        		console.log(result2);
        		console.log(result2[0].password)
        		console.log(req.body.p)
	       	 	if(result2[0].password == req.body.p){
	       	 		console.log('密码匹配')
	        		req.session.uname = req.body.name;
    				res.end(JSON.stringify(1))
	        
	        	}else{
	        		console.log('密码错误！')
	        		// res.redirect('/login');
	        		res.end(JSON.stringify(0));
	        	}
    		});
		}
	});
});

// 退出登录
router.get('/exit',function(req,res,err){
	req.session.uname='';
	console.log(req.session.uname)
	res.redirect('/')
})



// 点击注册保存数据并去到登录页面
router.post('/register',function(req,res,next){
	MongoClient.connect(url, function(err, db) {
	    if (err) throw err;
	    var dbase = db.db("blog");
	    var myobj = { 
	    	username: req.body.user,
	    	password: req.body.passwd2,
	    	pic:'/images/1.jpg',
	    };
	    dbase.collection("user").find({username:req.body.user}).toArray(function(err,result){
	    	console.log(result);
	    	if(result.length==0){
			    dbase.collection("user").insertOne(myobj, function(err, result) {
			        if (err) throw err;
			        console.log("注册成功！");
			        // res.redirect('/login');
			        res.end(JSON.stringify(1));
			    });
	    	}else{
	    		res.end(JSON.stringify(0));
	    		console.log('该用户名已存在')
	    	}

		});
	    
	});
})

// 去到登陆页面
router.get('/login',function(req,res,next){
	res.render('login')
})

// 去到博客详情页面
router.get('/article', function(req, res, next) {
	MongoClient.connect(url, function (err, db) {
	    if (err) throw err;
	    var dbase = db.db("blog");
	    dbase.collection("blog").find({title:req.query.title,author:req.query.author}).toArray(function(err,result) {
	        if (err) throw err;
	        // 找同一分类的文章
	        var type = result[0].type;
	        // 找同一作者的文章
	        var author = result[0].author;
	        dbase.collection("blog").find({author:author}).limit(3).toArray(function(err,result2){
		        // 渲染页面
		        dbase.collection("blog").find({type:type}).limit(3).toArray(function(err,result3){
		        	dbase.collection("user").find({username:req.session.uname}).toArray(function(err,result5){
			        	dbase.collection("comment").find({title:req.query.title,author:req.query.author}).sort({date:-1}).toArray(function(err,result4){
				    		res.render('article', {data:result,data2:result2,data3:result3,data4:result4,data5:result5,username:req.session.uname});
				    		db.close();
			    		});
		    		});
		    	})
	        })
	    });
	});
});

// 点击删除博客
router.post('/delarticle',function(req,res,next){
	console.log('delarticle');
	var myobj={
		"title":req.body.title,
		"author":req.session.uname
	}
	    MongoClient.connect(url, function (err, db) {
		    var dbase = db.db("blog");
		    dbase.collection("blog").deleteMany(myobj, function(err, res) {
		        if (err) throw err;
		    });
		});
	res.end();
})

// 点击删除评论
router.post('/delcomment',function(req,res,next){
	console.log('/delcomment')
	console.log(req.body.title+' '+req.body.author+' '+req.body.name+' '+req.body.content+' '+req.body.date+' '+req.body.zan)

	if((req.body.name!=req.body.author)){//不能删除非自己的评论
		res.end('0');
	}else{
		var myobj={
			"content":req.body.content,
			"author":req.session.uname,
			"name":req.body.name
		}
	    MongoClient.connect(url, function (err, db) {
		    var dbase = db.db("blog");
		    dbase.collection("comment").deleteMany(myobj, function(err, res) {
		        if (err) throw err;
		        console.log("删除的文档数量为: " + res.insertedCount);
		    });
		    res.end('1');
		});
	}
})

// 评论管理点击删除评论
router.post('/del_mycomment',function(req,res,next){
	console.log('/del_mycomment')
	console.log(req.body.title+' '+req.body.author+' '+req.body.name+' '+req.body.content+' '+req.body.date+' '+req.body.zan)
		var myobj={
			"content":req.body.content,
			"author":req.session.uname,
			"name":req.body.name
		}
	    MongoClient.connect(url, function (err, db) {
		    var dbase = db.db("blog");
		    dbase.collection("comment").deleteMany(myobj, function(err, res) {
		        if (err) throw err;
		        console.log("删除的文档数量为: " + res.insertedCount);
		    });
		    res.end('1');
		});
})

// 个人主页点击第几页
router.get('/myHome',function(req, res, next){
	console.log('myHome/get');
    MongoClient.connect(url, function (err, db) {
	    if (err) throw err;
	    const pageSize = 6;
	    var page;
	    page=req.query.page;
	    // 默认第一页
	    if(isNaN(page)){
	    	page = 1;
    	}
	    var dbase = db.db("blog");
	    dbase.collection("blog").find({author:req.session.uname}).toArray(function(err,result){
	    	var sumPage = Math.ceil(result.length/pageSize);
		    dbase.collection("blog").find({author:req.session.uname}).limit(pageSize).skip(pageSize*(page-1)).sort({"date":-1}).toArray(function(err,result2) {
		        if (err) throw err;
		        dbase.collection("blog").find({author:req.session.uname}).limit(pageSize).sort({"date":-1}).toArray(function(err,result4) {
		        	dbase.collection("blog").find({author:req.session.uname}).limit(3).sort({"date":-1}).toArray(function(err,result4) {
		        		// console.log(result4);
		        		res.render('myHome',{data:result2,data2:result4,sumPage:sumPage,username:req.session.uname})  
		        	});
	    	    	
	    	    });      
		    });
	    })
	});
})

// 去到写博客页面
router.get('/write',function(req, res, next){
		MongoClient.connect(url, function (err, db) {
		    if (err) throw err;
		    const pageSize = 6;
		    var page;
		    page=req.query.page;
		    // 默认第一页
		    if(isNaN(page)){
		    	page = 1;
	    	}
		    var dbase = db.db("blog");
		    dbase.collection("blog").find({author:req.session.uname}).toArray(function(err,result) {
		        if (err) throw err;
		        var sumPage = Math.ceil(result.length/pageSize);
		        dbase.collection("blog").find({author:req.session.uname}).limit(pageSize).skip(pageSize*(page-1)).sort({"date":-1}).toArray(function(err,result2) {
		            if (err) throw err;
		            dbase.collection("comment").find({author:req.session.uname}).sort({"date":-1}).toArray(function(err,result3) {
		                if (err) throw err;
		                res.render('write',{data:result2,data2:result3,sumPage:sumPage,username:req.session.uname})
		                // console.log(result2)
		            });
		        });
		    });
		});
	
})

// 去到资料设置页面
router.get('/setting',function(req, res, next){
    MongoClient.connect(url, function (err, db) {
	    var dbase = db.db("blog");
	    dbase.collection("user").find({username:req.session.uname}).toArray(function(err,result){
		        if (err) throw err;
	    	    res.render('setting',{data:result,username:req.session.uname})     
	    })
	});
})

// 保存修改去到setting
router.post('/save_change',function(req, res, next){
	// console.log(req.body.username)
    MongoClient.connect(url, function (err, db) {
	    var dbase = db.db("blog");
        console.log('修改前的req.session.uname：'+req.session.uname);
        	console.log(req.body.username+" "+req.body.email+' '+req.body.tel+' '+req.body.short)

        	var whereNameStr={"username":req.session.uname};
        	var updateNameStr={$set:{
        		"username":req.body.username,
        		"email":req.body.email,
        		"tel":req.body.tel,
        		"short":req.body.short
        	}}
        	var whereAuthorStr={"author":req.session.uname};
        	var upadteAuthorStr={$set:{
        		"author":req.body.username}}
           dbase.collection("user").updateMany(whereNameStr, updateNameStr, function(err, result) {
           		dbase.collection("blog").updateMany(whereAuthorStr, upadteAuthorStr, function(err2, result2) {
           			if (err) throw err
			        req.session.uname = req.body.username;
			        console.log('修改后的req.session.uname：'+req.session.uname);
			        res.redirect('/setting')  
		    	});
       		});
	});
})

// 修改密码
router.post('/change_pass',function(req, res, next){
	console.log('change_pass')
    MongoClient.connect(url, function (err, db) {
	    var dbase = db.db("blog");
    	var whereNameStr={"username":req.session.uname};
    	var updateNameStr={$set:{
    		"username":req.body.username,
    		"password":req.body.repassword
    	}}
    	var whereUserStr={"username":req.session.uname};
    	var upadteUserStr={$set:{
    		"password":req.body.repassword}}
       dbase.collection("user").find({username:req.session.uname}).toArray(function(err,result) {
       		if(result[0].password==req.body.prepassword){
       			dbase.collection("user").updateMany(whereUserStr, upadteUserStr, function(err2, result2) {
	       			if (err) throw err
			        console.log('修改成功！');
			    	// res.redirect('/myHome'); 
			    	res.end(JSON.stringify(1))
	    		});
       		}else{
       			console.log('输入的原始密码不正确');
       			res.end(JSON.stringify(0))
       		}
       		
   		});
	});
})

// 点击发布微博
router.post('/send_blog',function(req,res,next){
	console.log('/send_blog')
	    MongoClient.connect(url, function (err, db) {
		    var dbase = db.db("blog");
		    var myobj =  [{
		    	"author":req.session.uname,
		    	"title":req.body.title,
		    	"date":getNowDate(),
		    	"content":req.body.content,
		    	"type":'佛系时尚',
		    	"pic":'/images/1.jpg'
		    }]
		    dbase.collection("blog").insertMany(myobj, function(err, res) {
		        if (err) throw err;
		        console.log("插入的文档数量为: " + res.insertedCount);
		    });
		});
		res.redirect('/myHome');
})

//点击新增评论
router.post('/addcomment',function(req,res,next){
	console.log(req.body.title+' '+req.body.author+' '+req.body.name+' '+req.body.content+' '+req.body.date+' '+req.body.zan)
	var myobj=[{
		"title":req.body.title,
		"author":req.body.author,
		"name":req.body.name,
		"content":req.body.content,
		"date":req.body.date,
		"zan":req.body.zan
	}]
	    MongoClient.connect(url, function (err, db) {
		    var dbase = db.db("blog");
		    dbase.collection("comment").insertMany(myobj, function(err, res) {
		        if (err) throw err;
		        console.log("插入的文档数量为: " + res.insertedCount);
		    });
		});
	res.end('hello');
})

//点击删除评论
// router.post('/delcomment',function(req,res,next){
// 	console.log(req.body.title+' '+req.body.author+' '+req.body.name+' '+req.body.content+' '+req.body.date+' '+req.body.zan)
// 	var myobj={
// 		"title":req.body.title,
// 		"author":req.body.author,
// 		"name":req.body.name,
// 		"content":req.body.content
// 	}
// 	    MongoClient.connect(url, function (err, db) {
// 		    var dbase = db.db("blog");
// 		    dbase.collection("comment").deleteMany(myobj, function(err, res) {
// 		        if (err) throw err;
// 		        console.log("删除的文档数量为: " + res.insertedCount);
// 		    });
// 		});
// 	res.end('hello');
// })
module.exports = router;
